package com.hmdp.interceptor;

import com.hmdp.common.Constants;
import com.hmdp.common.HostHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Auther: 公众号/B站：是叶十三
 * @Date: 2022/11/9
 * @Description: com.hmdp.interceptor
 * @version: 1.0
 */
@Component
public class LoginInterceptor implements HandlerInterceptor, Constants {
//    private RedisTemplate redisTemplate;

//    public LoginInterceptor(RedisTemplate redisTemplate) {
//        this.redisTemplate = redisTemplate;
//    }
    // 错误写法，根本拿不到redisTemplate
//    @Autowired
//    private RedisTemplate redisTemplate;


    // 废弃
/*    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // 1、获取session
        HttpSession session = request.getSession();
        // 2、从session中获取用户信息
        UserDTO user = (UserDTO)session.getAttribute("user");
        // 3、判断用户是否已存在（已存在说明该用户已经登录了）
        //  3.1 不存在 直接拦截
        if (user == null){
            // 未授权用户无法发送该请求
            response.setStatus(401);
            return false;
        }
        // 3.2 存在，存入UserHoder中，并且放行
        HostHolder.saveUser(user);
        return true;
    }*/

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (HostHolder.getUser() == null){
            // 返回状态码
            response.setStatus(401);
            // 拦截
            return false;
        }
        return true;
    }

}
